// 同时发送异步代码的次数(当同时有多个请求时，控制刷新次数)
let ajaxTimes = 0;
// promise形式的wx.request
const request = (params) => {
    // 判断url字符串中是否含有/my/，请求的是私有属性。如果有，则带上header(内部包含token属性)
    let header = {...params.header};
    if(params.url.includes('/my/')){
        header['Authorization'] = wx.getStorageSync('token');;
    }
    // 每发送一次请求，ajaxTimes就加1
    ajaxTimes++;
    // 请求数据前，显示加载效果
    wx.showLoading({
        title: '玩命加载中...',
        mask: true,
    });
    const baseUrl = 'https://api-hmugo-web.itheima.net/api/public/v1';
    return new Promise((resolve, reject) => {
        wx.request({
            ...params,
            header,
            url: baseUrl + params.url,
            success: res => resolve(res),
            fail: err => reject(err),
            complete: () => {
                // 每完成一次请求，ajaxTimes就减1
                ajaxTimes--;
                // 当ajaxTimes为0时，才关闭加载效果
                if(ajaxTimes === 0){
                    wx.hideLoading();
                }
            }
        })
    })
}

// promise形式的wx.showModal
const showModal = ({content}) => {
    return new Promise((resolve, reject) => {
        wx.showModal({
            title: '提示',
            content,
            success: res => resolve(res),
            fail: err => reject(err)
        });
    })
}

// promise形式的wx.showToast
const showToast = (params) => {
    return new Promise((resolve, reject) => {
        wx.showToast({
            ...params,
            title: params.title,
            icon: params.icon,
            mask: params.mask,
            success: res => resolve(res),
            fail: err => reject(err)
        });
    })
}

// promise形式的wx.navigateTo
const navigateTo = ({url}) => {
    return new Promise((resolve, reject) => {
        wx.navigateTo({
            url,
            success: res => resolve(res),
            fail: err => reject(err)
        });
    })
}

// promise形式的wx.login
const login = () => {
    return new Promise((resolve, reject) => {
        wx.login({
            timeout:10000,
            success: res => resolve(res),
            fail: err => reject(err)
        });
    })
}

// promise形式的wx.requestPayment
const requestPayment = (pay) => {
    return new Promise((resolve, reject) => {
        wx.requestPayment({
            ...pay,
            success: res => resolve(res),
            fail: err => reject(err)
        });
    })
}

// promise形式的wx.getUserProfile
const getUserProfile = () => {
   return new Promise((resolve, reject) => {
        wx.getUserProfile({
            lang: 'zh_CN',
            desc: '用于完善会员资料',
            success: res => resolve(res),
            fail: err => reject(err)
        });
   }) 
 }

module.exports = {request, showModal, showToast, navigateTo, login, requestPayment, getUserProfile}

